package com.dream.inspect.modules.app.controller.scene;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dream.inspect.modules.app.controller.common.CommonMethod;
import com.dream.inspect.modules.business.dao.*;
import com.dream.inspect.modules.business.entity.*;
import com.dream.inspect.modules.business.service.SysMessageService;
import com.dream.inspect.modules.job.common.ScheduleCommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.dream.inspect.common.utils.DatetimeUtil;
import com.dream.inspect.common.utils.JsonUtil;
import com.dream.inspect.common.utils.R;
import com.dream.inspect.common.utils.StringUtil;
import com.dream.inspect.modules.app.controller.bean.SceneSupervisionBean;
import com.dream.inspect.modules.app.controller.bean.SupervisionQuestionBean;
import com.dream.inspect.modules.app.controller.bean.SupervisionSubmitBean;
import com.dream.inspect.modules.business.service.SuperviseQuestionModifyService;
import com.dream.inspect.modules.dream.dao.SuperviseQuestionMapper;
import com.dream.inspect.modules.dream.dao.SuperviseRecordMapper;
import com.dream.inspect.modules.sys.dao.SysDeptDao;
import com.dream.inspect.modules.sys.dao.SysUserDao;

/**
 * 现场督察
 *
 * @author zhouyb
 */
@RestController
@RequestMapping("/app/sceneSupervision/")
public class SceneSupervisionController{

    @Autowired
    SuperviseRecordMapper superviseRecordMapper;
    @Autowired
    SuperviseQuestionMapper superviseQuestionMapper;
    @Autowired
    SuperviseImageDao superviseImageDao;
    @Autowired
    SuperviseRecordDao superviseRecordDao;
    @Autowired
    SysDeptDao sysDeptDao;
    @Autowired
    SuperviseQuestionDao superviseQuestionDao;
    @Autowired
    SuperviseStandardDao superviseStandardDao;
    @Autowired
    SuperviseTempletDao superviseTempletDao;
    @Autowired
    SuperviseQuestionModifyService superviseQuestionModifyService;
    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    SuperviseProjectRecordDao superviseProjectRecordDao;
    @Autowired
    SysMessageService sysMessageService;
    @Autowired
    SuperviseProjectDao superviseProjectDao;
    @Autowired
    CommonMethod commonMethod;
    @Autowired
    SuperviseTargetDao superviseTargetDao;
    @Autowired
    ScheduleCommonMethod scheduleCommonMethod;

    /**
     * 完成拍摄
     *
     * @param request
     * @param response
     * @param json     json数据  {"beInspectedCorp":"被督查单位","beInspectedPolice":"被督查民警","bindingHours":"限制时间","description":"情况说明","inspectedPolice":"督察民警","inspectedProject":"检查项目项目","inspectedTime":"2018-06-17","rectificationType":"整改类型：1.限时整改，2.现场纠正"}
     * @return
     */
    @RequestMapping(value = "finishFilming", method = RequestMethod.POST)
    @Transactional(readOnly = false)
    public R finishFilming(HttpServletRequest request, HttpServletResponse response, String json) {
        System.out.println(json);
        try {
            SceneSupervisionBean supervisionBean = JsonUtil.jsonToBean(json, SceneSupervisionBean.class);
            Long createUser = Long.parseLong(supervisionBean.getCreateUser());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat dcsjSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date dcsj = sdf.parse(supervisionBean.getInspectedTime());

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("3", "新增数据失败");
        }
        return R.ok();
    }


    @RequestMapping(value = "/superviseSubmit")
    @Transactional(readOnly = false)
    public R superviseSubmit(HttpServletRequest request, HttpServletResponse response, String json) {
        System.out.println(json);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dcsjSdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date date = new Date();
        try {
            SupervisionSubmitBean supervisionSubmitBean = JsonUtil.jsonToBean(json, SupervisionSubmitBean.class);
            Long creatureUser = Long.parseLong(supervisionSubmitBean.getCreateUser());//提交用户
            Long dcdwId = Long.parseLong(supervisionSubmitBean.getDcdwId());//督查单位
            String dcry = supervisionSubmitBean.getDcry().replaceAll("[\\[\\]\"]","");//督查人员
            Long todcdwId = Long.parseLong(supervisionSubmitBean.getToDcdwId());//被督查单位
            Date dcsj = dcsjSdf.parse(supervisionSubmitBean.getDcTime());//督查时间
            String sfbc = "1";//是否备存
            String sfjzsjwc = supervisionSubmitBean.getSfjzsjwc();
            String projectId = supervisionSubmitBean.getProjectId();
            String dcfs = supervisionSubmitBean.getDcfs();//督察方式

            if("2".equals(dcfs) && StringUtil.isEmpty(projectId)){
            	return R.error("2","立项id不能为空");
            }
            String dcxlId = StringUtil.isNotEmpty(supervisionSubmitBean.getDcxl()) ? supervisionSubmitBean.getDcxl() : "";//督察小类Id
            String templetId = supervisionSubmitBean.getTempletId();//模板Id
            List<SupervisionQuestionBean> questionBeanList = supervisionSubmitBean.getSupervisionQuestionBeanList();
            int questionNum = questionBeanList.size();
            //插入督察记录
            Long recordId = insertSuperviseRecord(projectId, creatureUser, dcdwId, dcry, todcdwId, dcsj, sfjzsjwc, dcfs, sfbc, questionNum, templetId, dcxlId, json);
            List<SuperviseImageEntity> imageList = new ArrayList<SuperviseImageEntity>();
            int zgzt = 0;
            int wtNum = 0;
            //插入督察问题
            for (SupervisionQuestionBean q : questionBeanList) {
                Long questionId = Long.parseLong(q.getQuestionId());//检查项ID
                String toDcry = q.getToDcry().replaceAll("[\\[\\]\"]","");//被督查人员
                String zglx = q.getZglx();//整改类型(0：现场纠正，1：限时整改，2：无需整改)限时整改的时间最大30天
                Date zgjzrq = null;
                if ("1".equals(zglx)) {
                    zgzt = 1;//有限时整改
                    zgjzrq = plusDay(Integer.parseInt(q.getZgjzrq()), new Date());//整改截止时间
                }
                if (!"2".equals(zglx)) {
                    wtNum++;
                }
                String qksm = q.getQksm();//情况说明
                List<SuperviseImageEntity> superviseImageEntityList = q.getSuperviseImageEntityList();
                Long queationLinkId = 0L;
                queationLinkId = insertSuperviseQuestion(creatureUser, dcdwId, dcry, todcdwId, dcsj, recordId, questionId, toDcry, zglx, zgjzrq, qksm, sfbc);
                if("1".equals(zglx) && !("1".equals(q.getZgjzrq()))){//限时整改且整改天数大于1 发送整改截止前36小时消息
                    scheduleCommonMethod.addTimeMessage(zgjzrq,"1",questionId +"," +todcdwId);
                }
                if ("0".equals(zglx) && "1".equals(sfbc)) {//现场纠正要生成提交整改记录
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("dcQuestionId", String.valueOf(queationLinkId));
                    params.put("dcRecordId", String.valueOf(recordId));
//                params.put("modifyTime",DatetimeUtil.getStringDate());
                    params.put("toDcry", toDcry);
                    params.put("fkry", getUserNameById(supervisionSubmitBean.getCreateUser()));
                    params.put("fksj", DatetimeUtil.getStringDate());
                    params.put("fkdw", getDeptNameById(dcdwId));//此时反馈单位是督查单位
                    params.put("zgfknr", "现场整改");
                    params.put("userId", supervisionSubmitBean.getCreateUser());
                    superviseQuestionModifyService.insertFeedBackSuperviseQuestionModify(params);
                }
                //插入照片
                for (SuperviseImageEntity image : superviseImageEntityList) {
                    image.setWtglId(queationLinkId);//问题关联Id
                    image.setPicType("1");//问题照片
                    if (image.getPicUrl().endsWith("/")){//区分(0：照片，1：录像)
                        image.setPicUrl(image.getPicUrl()+image.getPicName());
                    }
                    image.setCreateUser(creatureUser);
                    image.setUpdateUser(creatureUser);
                    image.setUpdateTime(date);
                    image.setCreateTime(date);
//                superviseImageDao.insert(image);
                    imageList.add(image);
                }
            }
            if (imageList != null && imageList.size() > 0) {
                superviseImageDao.insertImageList(imageList);
            }

            //非问题随拍查询模板中没有问题的检查项
//            if (!"1".equals(dcfs)) {
//                List<Long> noQuestionList = superviseStandardDao.getNoQuestionIdList(templetId, recordId, dcxlId);
//                if (noQuestionList != null && noQuestionList.size() > 0) {
//                    Map<String, Object> map = new HashMap<String, Object>();
//                    map.put("list", noQuestionList);
//                    map.put("rId", recordId);
//                    map.put("userId", creatureUser);
//                    map.put("dcsj", dcsj);
//                    map.put("zglx", "2");//无需整改
//                    map.put("date", date);
//                    map.put("modifyStatus", "1");//整改状态(0：待整改，1：无整改，2：已整改，3：备存无整改，4：备存待整改)
//                    superviseQuestionDao.insertQuestionList(map);
//                }
//            }
            if(questionNum != 0){//提交问题数不为0
                SuperviseRecordEntity r = new SuperviseRecordEntity();
                if (zgzt == 1) {//有问题 有限时整改
                    if(questionNum != wtNum){// 有无需整改问题
                        r.setDcwts(Long.valueOf(wtNum));
                    }
                    r.setId(recordId);
                    r.setModifyStatus("0");

                } else if (zgzt == 0 ){// 有问题 无限时整改
                    r.setId(recordId);
                    if(questionNum == wtNum) {// 全是现场整改
                        r.setModifyStatus("2");
                    }else{
                        r.setDcwts(0L);//整改状态(0：待整改，1：无整改，2：已整改)
                        if (wtNum == 0) {//全是无需整改
                            r.setModifyStatus("1");
                        }else{//现场 + 无需
                            r.setModifyStatus("2");
                        }
                    }
                }
                superviseRecordDao.updateById(r);
            }


            if ("2".equals(dcfs)) {//专项督查需要生成对应的督查记录
                SuperviseProjectRecordEntity r = new SuperviseProjectRecordEntity();
                r.setProjectId(Long.parseLong(projectId));
                r.setCzdwId(dcdwId);
                r.setSfjzsjwc(sfjzsjwc);
                r.setCzzt("5");
                r.setCzryName(getUserNameById(supervisionSubmitBean.getCreateUser()));
                r.setCreateUser(creatureUser);
                r.setUpdateUser(creatureUser);
                r.setUpdateTime(date);
                r.setCreateTime(date);
                superviseProjectRecordDao.insert(r);
                //实施单位改为已实施
                SuperviseTargetEntity superviseTargetEntity = new SuperviseTargetEntity();
                superviseTargetEntity.setProjectId(Long.parseLong(projectId));
                superviseTargetEntity.setToSsdwId(dcdwId);
                superviseTargetDao.updateSsStatus(superviseTargetEntity);
                //执行督查，通知专项发布单位
                Map<String, String> map = new HashMap<String, String>();
                String deptId = String.valueOf(superviseProjectDao.selectAllById(projectId).getZbdwId());
                String noticeTitle = "您的专项被执行！";
                String noticeContent = getDeptNameById(dcdwId) + "执行了专项" + getProjectNameById(projectId) + "督察任务！";
                insertMessgae(noticeTitle, noticeContent, String.valueOf(creatureUser), deptId);
            }
            //插入被督察单位系统消息
            String dcmc = getDcmc(dcdwId, templetId, sfbc, dcfs);
            Map<String, String> map = new HashMap<String, String>();
            String deptId = supervisionSubmitBean.getToDcdwId();
            String noticeTitle = "您的单位有新的督察记录！";
            String noticeContent = "您的单位有新的被督察记录" + dcmc + "，含" + questionNum + "个问题待整改！";
            insertMessgae(noticeTitle, noticeContent, String.valueOf(creatureUser), deptId);
            //通知管辖单位
            Long gxDeptId = getQhIdBydeptId(todcdwId);
            if (!dcdwId.equals(gxDeptId)) {
                noticeTitle = "您管辖的单位有新的督察记录！";
                noticeContent = getDeptNameById(todcdwId) + "单位有新的被督察记录" + dcmc + "，含" + questionNum + "个问题,请关注！";
                insertMessgae(noticeTitle, noticeContent, String.valueOf(creatureUser), String.valueOf(gxDeptId));
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("3", "数据保存失败");
        }
        return R.ok().put("data", "数据上传成功");
    }

    ;

    /**
     * 新增督查记录
     *
     * @param creatureUser 提交用户
     * @param dcdwId       督查单位ID
     * @param dcry         督查用户
     * @param todcdwId     被督查单位
     * @param dcsj         督查时间
     * @param sfjzsj       是否截止时间完成
     * @param dcfs         督查方式
     * @param sfbc         是否备存
     * @param num          问题数
     * @return 督查记录Id
     */
    private Long insertSuperviseRecord(String projectId, Long creatureUser, Long dcdwId, String dcry, Long todcdwId, Date dcsj, String sfjzsj, String dcfs, String sfbc, int num, String templetId, String dcxl, String json) throws Exception {
        SuperviseRecordEntity superviseRecordEntity = new SuperviseRecordEntity();
        superviseRecordEntity.setDcwts((long) num);//督查问题数
        if (StringUtil.isNotEmpty(dcfs)) {
            superviseRecordEntity.setDcfs(dcfs);//督查记录方式(1：问题随拍，2：专项督察，3：队伍管理，4：执法执勤，5：社会管控，6：其他督查)
        }
        if (StringUtil.isNotEmpty(projectId)) {
            superviseRecordEntity.setProjectId(Long.parseLong(projectId));
        }
        superviseRecordEntity.setDcdwId(dcdwId);//督查单位
        superviseRecordEntity.setDcry(dcry);//督查人员ID（多个用逗号隔开）
        superviseRecordEntity.setToDcdwId(todcdwId);//被督查单位ID
        superviseRecordEntity.setGxdwId(getQhIdBydeptId(todcdwId));//管辖单位
//        superviseRecordEntity.setDcry();//被督查单位负责人ID
        superviseRecordEntity.setDcTime(dcsj);//督查时间
        superviseRecordEntity.setModifyStatus(num == 0 ? "1" : "0");//整改状态(0：待整改，1：无整改，2：已整改)
        superviseRecordEntity.setSfjzsjwc(sfjzsj);//是否截止时间完成0：是，1：未完成)
        superviseRecordEntity.setSfbc(sfbc);//是否备存(0：是，1：否)
        superviseRecordEntity.setTempletId(Long.parseLong(templetId));//模板Id,问题随拍为0
        if (StringUtil.isNotEmpty(dcxl)) {
            superviseRecordEntity.setMinQuestionId(dcxl);//督查小类
        }
        superviseRecordEntity.setJsonRecord(json);
        superviseRecordEntity.setCreateUser(creatureUser);//创建用户
        superviseRecordEntity.setCreateTime(new Date());//创建时间
        superviseRecordEntity.setCreateUser(creatureUser);//更新用户
        superviseRecordEntity.setUpdateTime(new Date());//更新时间
        superviseRecordEntity.setDcmc(getDcmc(dcdwId, templetId, sfbc, dcfs));//督查名称
        superviseRecordDao.insert(superviseRecordEntity);
        return superviseRecordEntity.getId();
    }

    /**
     * 插入督查问题数据
     *
     * @param creatureUser
     * @param dcdwId
     * @param dcry
     * @param todcdwId
     * @param dcsj
     * @param recordId
     * @param questionId
     * @param toDcry
     * @param zglx
     * @param zgjzrq
     * @param qksm
     * @return
     * @throws Exception
     */
    private Long insertSuperviseQuestion(Long creatureUser,
                                         Long dcdwId,
                                         String dcry,
                                         Long todcdwId,
                                         Date dcsj,
                                         Long recordId,
                                         Long questionId,
                                         String toDcry,
                                         String zglx,
                                         Date zgjzrq,
                                         String qksm,
                                         String sfbc) throws Exception {
        SuperviseQuestionEntity questionEntity = new SuperviseQuestionEntity();
        questionEntity.setCreateUser(creatureUser);
        questionEntity.setUpdateUser(creatureUser);
        questionEntity.setUpdateTime(new Date());
        questionEntity.setCreateTime(new Date());
        questionEntity.setDcdw(getDeptNameById(dcdwId));
        questionEntity.setDcry(dcry);
        questionEntity.setToDcdw(getDeptNameById(todcdwId));
        questionEntity.setToDcry(toDcry);
//        questionEntity.setToDcdwfzr(null);//被督查单位负责人
        questionEntity.setZglx(zglx);
        if ("1".equals(zglx)) {//限时整改
            questionEntity.setModifyStatus("0");
            questionEntity.setZgjzrq(zgjzrq);
        } else if("0".equals(zglx)){//现场整改
            questionEntity.setModifyStatus("2");
        } else {//无问题  则为无整改
            questionEntity.setModifyStatus("1");
        }

        questionEntity.setQksm(qksm);
        questionEntity.setQuestionId(questionId);
        questionEntity.setDcRecordId(recordId);
        questionEntity.setDcsj(dcsj);

       // questionEntity.setModifyStatus("1".equals(sfbc) ? ("0".equals(zglx) ? "2" : "0") : "4");//当督查方式为现场纠正时，整改状态为已整改
        superviseQuestionDao.insert(questionEntity);
        return questionEntity.getId();

    }


    /**
     * 查询部门name
     */
    public String getDeptNameById(Long id) {
        return sysDeptDao.queryDeptNameById(id);
    }

    /**
     * 查询模板名称
     *
     * @param id
     * @return
     */
    public String getTempNameById(String id) {
        return superviseTempletDao.selectById(id).getMbmc();
    }

    public String getUserNameById(String id) {
        return sysUserDao.selectById(id).getName();
    }

    public Long getQhIdBydeptId(Long id) {
        return sysDeptDao.selectById(id).getParentId();
    }

    //查询专项名称
    public String getProjectNameById(String id) {
        return superviseProjectDao.selectAllById(id).getTitleName();
    }

    private void insertMessgae(String noticeTitle, String noticeContent, String userId, String deptId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("noticeTitle", noticeTitle);
        map.put("noticeContent", noticeContent);
        map.put("userId", userId);
        map.put("deptId", deptId);
        map.put("roles", commonMethod.getRolesByDeptId(deptId));
        sysMessageService.insertMessage(map);
    }

    /**
     * @param dcdwId
     * @param templetId
     * @param sfbc
     * @return 是备存 返回模板名称  不是备存 返回  单位名-模板名
     */
    public String getDcmc(Long dcdwId, String templetId, String sfbc, String dcfs) {
        if ("2".equals(dcfs)) {
            return "0".equals(sfbc) ? getTempNameById(templetId) : (getDeptNameById(dcdwId) + "-" + getTempNameById(templetId));
        } else if ("1".equals(dcfs)) {
            return getDeptNameById(dcdwId) + "问题随拍";
        } else {
            return "0".equals(sfbc) ? getName(dcfs) : (getDeptNameById(dcdwId) + "-" + getName(dcfs));
        }

    }

    public String getName(String code) {
        switch (code) {
            case "3":
                return "队伍管理督察";
            case "4":
                return "执法执勤督察";
            case "5":
                return "社会管控督察";
            case "6":
                return "其它督察";
            case "7":
                return "每日必查";
        }
        return "";
    }


    public Date getBackupOverdueTime(Date dcsj) {
        return plusDay(3, dcsj);
    }


    /**
     * 指定日期加上天数后的日期
     *
     * @param num 为增加的天数
     * @param d   创建时间
     * @return
     * @throws
     */
    public Date plusDay(int num, Date d) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(d);
        System.out.println("现在的日期是：" + currdate);
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        return ca.getTime();
    }
}
